package top;

import java.util.HashMap;

/**
 * @author chenyw
 * @date 2022/7/12 17:08
 * @description
 */
public class Top166fractionToDecimal {
    public String fractionToDecimal(int numerator, int denominator) {
        long a = numerator;
        long b = denominator;
        StringBuffer sb = new StringBuffer();
        //处理符号
        if ((a > 0 && b < 0) || (a < 0 && b > 0)) {
            sb.append("-");
        }
        a = Math.abs(a);
        b = Math.abs(b);
        //处理整数
        sb.append(String.valueOf(a / b));
        if (a % b == 0) {
            return sb.toString();
        }
        sb.append(".");
        HashMap<Long, Integer> map = new HashMap<>();
        //处理小数部分
        //余数为0或者小数出现循环时跳出
        while ((a = (a % b) * 10) > 0 && !map.containsKey(a)) {
            sb.append(String.valueOf(a / b));
            map.put(a, sb.length() - 1);
        }
        if (a == 0) {
            return sb.toString();
        }
        return sb.insert(map.get(a).intValue(),"(").append(")").toString();
    }
}
